<script setup lang="ts">
import {
  addlmsSupplierConfig,
  supplierOptions,
  inventoryTypeOptions,
  updateConfig,
} from "@/api/DataIntegration/interface/index";

import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import useUserStore from "@/store/modules/user";
import dayjs from "dayjs";
let useStore = useUserStore();

const loading = ref(false);

const ruleFormRef = ref(); //弹框表单
const ruleForm = ref({
  connectInfo: [] as Array<{ key: string; value: string }>,
} as any);
// 处理提交时的数据转换
const convertToObject = (arr: Array<{ key: string; value: string }>) => {
  return arr.reduce((acc: Record<string, string>, item) => {
    if (item.key) acc[item.key] = item.value;
    return acc;
  }, {});
};
/**
 * 关闭弹框
 */
const close = () => {
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
  ruleForm.value = {} as any;
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  try {
    loading.value = true;
    const isValid = await ruleFormRef.value.validate();
    if (isValid) {
      // 转换动态表单数据为对象
      const formData = {
        ...ruleForm.value,
        connectInfo: convertToObject(ruleForm.value.connectInfo),
      };

      const res = await addlmsSupplierConfig(formData);
      if (res.code === 200) {
        ElMessage.success("保存成功");
        // 关闭对话框并重新查询列表数据
        close();
        const { data } = await updateConfig(useStore.encryptedData);
        // 将JSON字符串转换为数组格式++
        const parseConfig = (config: string) => {
          try {
            const obj = JSON.parse(config);
            return Object.entries(obj).map(([key, value]) => ({ key, value }));
          } catch {
            return [];
          }
        };

        ruleForm.value = {
          ...data,
          connectInfo: parseConfig(data.connectInfo),
        };
        loading.value = false;
      } else {
        ElMessage.error(res.msg);
        loading.value = false;
      }
    }
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};

const inventoryOptions = ref([] as any);
const supplierOpt = ref([] as any);
onMounted(async () => {
  const res = await inventoryTypeOptions(useStore.encryptedData);
  inventoryOptions.value = res.data;
  const ress = await supplierOptions(useStore.encryptedData);
  supplierOpt.value = ress.data;
  const { data } = await updateConfig(useStore.encryptedData);
  // 将JSON字符串转换为数组格式++
  const parseConfig = (config: string) => {
    try {
      const obj = JSON.parse(config);
      return Object.entries(obj).map(([key, value]) => ({ key, value }));
    } catch {
      return [];
    }
  };

  ruleForm.value = {
    ...data,
    connectInfo: parseConfig(data.connectInfo),
  };
});

/**
 * 时间格式
 */

const formatDateTime = () => {
  const formattedDateTime = dayjs(ruleForm.value.startTime).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  ruleForm.value.startTime = formattedDateTime;
};
// 根据供应商选择变化处理连接信息回显
const handleSupplierChange = (supplierId: string) => {
  // 清空现有连接信息
  ruleForm.value.connectInfo = [];

  // 找到选中的供应商
  const selectedSupplier = supplierOpt.value.find(
    (item: any) => item.id === supplierId
  );
  if (!selectedSupplier?.formConfig) return;

  try {
    // 解析 formConfig（字符串或对象）
    const formConfig =
      typeof selectedSupplier.formConfig === "string"
        ? JSON.parse(selectedSupplier.formConfig)
        : selectedSupplier.formConfig;

    // 递归提取所有键名
    const extractAllKeys = (obj: any): string[] => {
      const keys: string[] = [];
      for (const key in obj) {
        if (typeof obj[key] === "object" && obj[key] !== null) {
          keys.push(...extractAllKeys(obj[key])); // 递归处理嵌套对象
        } else {
          keys.push(key); // 添加当前层级的键
        }
      }
      return keys;
    };

    // 获取所有唯一键名
    const allKeys = [...new Set(extractAllKeys(formConfig))];

    // 生成键值对
    allKeys.forEach((key) => {
      ruleForm.value.connectInfo.push({
        key, // 显示所有键名
        value: "", // 值留空
      });
    });
  } catch (error) {
    console.error("解析 formConfig 失败", error);
  }
};
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        label-width="150px"
        status-icon
      >
        <el-form-item
          label="图书馆里系统供应商"
          prop="supplierId"
          ref="supplierIdref"
        >
          <el-select
            v-model="ruleForm.supplierId"
            placeholder="请选择供应商"
            style="width: 30%"
            @change="handleSupplierChange"
          >
            <el-option
              v-for="item in supplierOpt"
              :key="item.value"
              :label="item.supplierName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="ruleForm.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择时间"
            @change="formatDateTime"
            style="width: 30%"
          />
        </el-form-item>
        <el-form-item label="时间类型" prop="typeId">
          <el-select
            v-model="ruleForm.typeId"
            placeholder="请选择时间类型"
            style="width: 30%"
          >
            <el-option
              v-for="item in inventoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="连接信息">
          <div
            v-for="(item, index) in ruleForm.connectInfo"
            :key="index"
            class="key-value-item"
          >
            <el-input
              v-model="item.key"
              placeholder="键"
              style="width: 200px; margin-right: 10px"
            />
            <el-input
              v-model="item.value"
              placeholder="值"
              style="width: 200px; margin-right: 10px"
            />
          </div>
        </el-form-item>
        <el-form-item label="定时同步" prop="status">
          <el-radio-group v-model="ruleForm.scheduleFlag">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">保 存</el-button>
          <el-button @click="close">重 置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}

.key-value-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.dialog-footer {
  margin-top: 10%;
  display: flex;
  justify-content: center; /* 水平居中 */
  gap: 10px; /* 按钮间距 */
}
</style>
